//
//  YLLLoginViewModel.swift
//  YLLSina
//
//  Created by 于玲玲 on 16/7/31.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class YLLLoginViewModel: NSObject {
    
    static let shareInstance: YLLLoginViewModel = YLLLoginViewModel()

    var model: YLLUserInfoModel?
    
    var access_token: String?{
    
    return model?.access_token
    }
    
    var isLogin: Bool{
        return model?.access_token == nil ? false : true
    }
    
    private override init() {
        model = YLLUserInfoModel.readModel()
    }
    
    func loadToken(code: String,success: ()->(),failed: (messgae: String)->()){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id":AppKey,
                      "client_secret":AppSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri": RedrectURL
        ]
        
        
        printLog(params)
        
        YLLHTTPCient.shareInstance.request(.POST, URLString: urlString, parameters: params, progress: nil, success: { (_, JSON) in
            printLog(JSON)
            
            guard let json = JSON else{
                
                return
                
            }
            
            let dict = json as![String :AnyObject]
            
            let model = YLLUserInfoModel(dict: dict)
            
            printLog(model.access_token)
            
            
            self.loadPersonalInfo(model,success:success,failed:failed)
            
            }) { (_, error) in
                failed(messgae: error.description)
        }
        
        
    }
    
    private func loadPersonalInfo(model: YLLUserInfoModel,success: ()->(),failed:(message: String)->()){
        
        
         let urlString = "https://api.weibo.com/2/users/show.json"
        
        
        guard let token = model.access_token,uid = model.uid else{
            
            return
            
        }
        
        let params = ["access_token": token,
                      "uid": uid
        ]
        
        printLog(params)
        
        YLLHTTPCient.shareInstance.request(.GET, URLString: urlString, parameters: params, progress: nil, success: { (_, JSON) in
            
            printLog(JSON)
            
            guard let json = JSON as?[String: AnyObject] else{
                return
                
            }
            
            model.screen_name = json["screen_name"] as? String
            
            model.profile_image_url = json["profile_image_url"] as? String
            
            printLog(model.profile_image_url)

            self.model = model
            
            model.saveModel()
            
            success()
            
            
            }) { (_, error) in
                failed(message: error.description)
        }
        
        
        
    }
    
    
}
